package com.treeHole.treeHoleServer.service.impl;

import com.treeHole.treeHoleServer.mapper.UserMapper;
import com.treeHole.treeHoleServer.pojo.User;
import com.treeHole.treeHoleServer.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;


@Slf4j
@Service
public class UserServiceImpl implements UserService {


    @Autowired
    UserMapper userMapper;

    @Override
    public Integer verifyPassword(String userEmail, String password) {
        Integer resultUserId = 0;
        List<User> resultList=userMapper.selectUserByEmailAndPassword(userEmail, password);
        log.info("服务层收到验证密码请求,获得的用户列表:{}(应为1)",resultList.size());
        if(!resultList.isEmpty()){
            resultUserId=resultList.get(0).getUserId();
        }
        return resultUserId;
    }

    @Override
    public Integer createUser(String userEmail, String password) {
        log.info("服务层收到创建用户请求,userEmail:{}",userEmail);
        List<User> resultList=userMapper.searchUserByEmail(userEmail);
        if(!resultList.isEmpty()){
            log.info("重复注册的邮箱!");
            return 0;
        }

        User user=new User();
        user.setEmail(userEmail);
        user.setPassword(password);
        user.setRegisterDate(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        userMapper.insertUser(user);
        log.info("服务层收到创建用户请求,新创建的用户id为{}",user.getUserId());
        return user.getUserId();
    }

    @Override
    public Integer getUserId(String userEmail) {
        Integer resultUserId = 0;
        List<Integer> resultList=userMapper.getUserIdByEmail(userEmail);
        log.info("服务层收到获取用户id请求,获得的用户列表:{}(应为1)",resultList.size());
        if(!resultList.isEmpty()){
            resultUserId=resultList.get(0);
        }
        return resultUserId;
    }

    @Override
    public int modifyUserPassword(String userEmail, String NewPassword) {
        int result=userMapper.modifyUserPassword(userEmail,NewPassword);
        log.info("服务层收到修改用户密码请求,修改结果:{}",result);
        return result;
    }

    @Override
    public int userLogin(String userEmail) {
        int result=userMapper.modifyUserLastLoginTime(
                userEmail,
                LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        log.info("服务层收到更新用户最新登录时间请求,修改结果:{}",result);
        return result;
    }
}
